#include "CarAssignment.h"
#include <fstream>
#include <iostream>
#include <cctype>  // 用于tolower()函数
using namespace std;

// 将分配信息保存到文件
void saveToFile(const vector<CarAssignment>& assignments) {
    ofstream outFile("car_data.txt");  // 覆盖模式写入数据
    if (!outFile) {
        cerr << "文件保存失败！" << endl;
        return;
    }

    for (const auto& assignment : assignments) {
        outFile << assignment.car.carID << endl;
        outFile << assignment.car.chassisID << endl;
        outFile << assignment.student.studentID << endl;
        outFile << assignment.student.name << endl;
        outFile << "--------------------------" << endl;
    }

    outFile.close();
    cout << "信息已保存至 car_data.txt 文件。" << endl;
}

// 从文件读取并逐步显示分配信息
void displayFromFile() {
    ifstream inFile("car_data.txt");
    if (!inFile) {
        cerr << "无法打开文件！" << endl;
        return;
    }

    vector<CarAssignment> assignments;
    CarAssignment temp;
    string line;

    // 读取文件中的数据
    while (getline(inFile, temp.car.carID)) {
        getline(inFile, temp.car.chassisID);
        getline(inFile, temp.student.studentID);
        getline(inFile, temp.student.name);
        getline(inFile, line);  // 跳过分隔线
        assignments.push_back(temp);
    }

    inFile.close();

    // 显示读取到的信息
    int index = 0;
    while (true) {
        if (index < 0) index = 0;
        if (index >= assignments.size()) index = assignments.size() - 1;

        // 显示车辆和学生信息
        cout << "车辆编号: " << assignments[index].car.carID << endl;
        cout << "底盘编号: " << assignments[index].car.chassisID << endl;
        cout << "学生学号: " << assignments[index].student.studentID << endl;
        cout << "学生姓名: " << assignments[index].student.name << endl;
        cout << "--------------------------" << endl;

        // 用户输入控制
        char command;
        cout << "按n显示下一辆，按p显示上一辆，按q退出: ";
        cin >> command;
        command = tolower(command);  // 转换用户输入为小写

        if (command == 'n' && index < assignments.size() - 1) {
            index++;
        } else if (command == 'p' && index > 0) {
            index--;
        } else if (command == 'q') {
            break;
        }
    }
}
